<template>
  <div class="drawing-board-container">
    <div class="drawing-header">
      <input type="text" v-model="title" />
    </div>
    <div class="drawing-handle" style="">
      <div class="handle-left">
        <div class="handle-item" @click="undodrawing">撤销</div>
        <div class="handle-item" @click="redodrawing">恢复</div>
        <div class="handle-item" @click="cleanboard">清空</div>
        <div class="handle-item set-context-color" @click="setContextColor">
          <span :style="{ color: color }">颜色</span>
          <div class="context-color-picker">
            <el-color-picker
              ref="colorPicker"
              v-model="color"
              :show="showColorPicker"
              @change="handleChangeColor"
            ></el-color-picker>
          </div>
        </div>
        <div class="handle-item" @click="contextFine">细体</div>
        <div class="handle-item" @click="contextBulky">粗体</div>
        <div class="handle-item" @click="rubber">橡皮</div>

        <div class="handle-item" @click="downloadImage">下载</div>
      </div>
      <div class="handle-right">
        <div class="handle-item" @click="savedrawing">保存</div>
        <div class="handle-item" @click="backdraw">返回</div>
      </div>
    </div>
    <!--中间画板-->
    <div class="drawing-board" >
      <div
        id="container"
        ref="container"
        style="width: 100%; height: 100%"
    
      ></div>
    </div>
    
  </div>
</template>

  <script setup>
import { ref, reactive, onMounted, unref } from "vue";
import { useRoute, useRouter } from "vue-router";
import Board from "./drawing-board.js";
import request from "utils/request";
import { ElMessage, ElLoading, ElColorPicker } from "element-plus";

// const customCursorImage = require("src/assets/xiongmao.png");

const qiniuLink = ref("");

const colorPicker = ref();
const showColorPicker = ref(false);
const color = ref("#000000");

function handleChangeColor(color) {
  drawboard.setContextColor(color);
  console.log("选中的颜色: " + color);
}

//1,先将base64转换为blob
function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
//2,再将blob转换为file
function blobToFile(theBlob, fileName) {
  theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
  theBlob.name = fileName; // 文件名
  return new File([theBlob], fileName, {
    type: theBlob.type,
    lastModified: Date.now(),
  });
}

const route = useRoute();
const router = useRouter();
const title = ref("");

const container = ref(null);
let drawboard = null;
onMounted(async () => {
  // 新建一个画板
  drawboard = new Board(container.value);

  if (route.query.id) {
    let ret = await request.get(`/draw/${route.query.id}`);
    if (ret.code == 200) {
      title.value = ret.data.title;
      qiniuLink.value = ret.data.content;
      drawboard.echoImage(ret.data.content || "");
    }
  }
});
async function savedrawing() {
  const drawdata = drawboard.getImage();
  let formdata = new FormData();
  const timestamp = new Date().valueOf();
  let filename = timestamp;
  // console.log(drawdata);

  // url.value=drawdata
  formdata.append("drawPictureId", filename);
  formdata.append("drawPictureData", drawdata);
  // formdata.append("drawPictureData",drawdata.substring(22));

  if (!title.value || !drawdata) {
    ElMessage({
      type: "error",
      message: "数据信息不全，请完善！",
      showClose: true,
      duration: 1000,
    });
    return false;
  }

  const loading = ElLoading.service({
    lock: true,
    text: "资源较大，请耐心等待......",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let file = blobToFile(dataURLtoBlob(drawdata), "draw");

  const imgData = new FormData(); // 创建form对象
  imgData.append("file", file); // 通过append向form对象添加数据
  imgData.append("namespace", "draw");
  const config = {
    headers: { "Content-Type": "multipart/form-data" },
  };
  let ret = await request.upload("/upload", imgData, config);
  loading.close();
  let res = null;
  if (ret.code == 200) {
    if (route.query.id) {
      res = await request.patch(`/draw/${route.query.id}`, {
        title: title.value,
        content: ret.data,
      });
      if (res.code == 200) {
        /**
         * 删除原始七牛云资源
         */
        try {
          let qiniuSplit = unref(qiniuLink.value).split("suzhidong.cn/");
          await request.post(`/components/qiniu/remove`, {
            key: qiniuSplit[1],
          });
        } catch (error) {
          console.log(error);
        }

        qiniuLink.value = res.data.content;
        ElMessage({
          type: "success",
          message: "success",
          showClose: true,
          duration: 500,
        });
      } else {
        ElMessage({
          type: "error",
          message: "资源生成失败",
          showClose: true,
          duration: 1000,
        });
      }
    } else {
      res = await request.post("/draw/add", {
        title: title.value,
        content: ret.data,
      });
      if (res.code == 200) {
        qiniuLink.value = res.data.content;
        ElMessage({
          type: "success",
          message: "success",
          showClose: true,
          duration: 500,
        });
      } else {
        ElMessage({
          type: "error",
          message: "资源生成失败",
          showClose: true,
          duration: 1000,
        });
      }

      router.replace({
        path: "/draw-image",
        query: {
          id: res.data.id,
        },
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "资源生成失败",
      showClose: true,
      duration: 1000,
    });
    return false;
  }
}
function contextFine(){
  drawboard.contextFine();  
}
function contextBulky(){
  drawboard.contextBulky();
}
function redodrawing() {
  drawboard.redo();
}
function undodrawing() {
  drawboard.undo();
}
function setContextColor() {
  showColorPicker.value = true;
}
function cleanboard() {
  drawboard.cleanboard();
}
function downloadImage() {
  drawboard.downloadImage();
}
function initContext2DStyle() {
  drawboard.initContext2DStyle();
}
function rubber() {
  drawboard.rubber();
}
function backdraw() {
  router.back();
}
</script>
  
  <style lang="scss">
* {
  box-sizing: border-box;
}
// * {
//   cursor: url("src/assets/xiongmao.png"), auto;
// }

.drawing-board-container {
}
.drawing-header {
  width: 100%;
  min-height: 50px;
  position: fixed;
  top: 0px;
  left: 0px;
  text-align: center;
  line-height: 50px;
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  background: white;
  & > input {
    width: 100%;
    height: 50px;
    text-align: center;
    border: none; /* 去除边框 */
    background-color: transparent; /* 透明背景色 */
    box-shadow: none; /* 无阴影效果 */
    outline: none;
    font-size: 20px;
  }
  & > input:focus {
    border: none; /* 去除边框 */
    background-color: transparent; /* 透明背景色 */
    box-shadow: none; /* 无阴影效果 */
    outline: none;
  }
}
.drawing-handle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  min-height: 50px;
  position: fixed;
  bottom: 0px;
  left: 0px;
  border-bottom: unset;
  padding-left: 20px;
  box-shadow: 0px -2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  background: white;
  .handle-left {
    display: flex;
    // flex-direction: column;
    align-items: center;
  }
  .handle-right {
    display: flex;
    // flex-direction: column;
    align-items: center;
  }
  & .handle-item {
    line-height: 32px;
    font-size: 14px;
    color: 'black';
    cursor: pointer;
    margin-right: 18px;
  }
}
.drawing-board {
  width: 100%;
  height: 3000px;
  // border: 1px #00000029 solid;
  // margin: 10px;
  padding: 50px 0 50px;
}

.set-context-color {
  position: relative;
}
.context-color-picker {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
* {
  // cursor: url("src/assets/xiongmao.png"), auto;
}
</style>